package com.example.whm;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Application;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.app.ProgressDialog;
import org.holoeverywhere.preference.SharedPreferences;
import org.holoeverywhere.widget.AdapterView;
import org.holoeverywhere.widget.ArrayAdapter;
import org.holoeverywhere.widget.CheckBox;
import org.holoeverywhere.widget.LinearLayout;
import org.holoeverywhere.widget.ListPopupWindow;
import org.holoeverywhere.widget.ListView;
import org.holoeverywhere.widget.Spinner;
import org.holoeverywhere.widget.TextView;
import org.holoeverywhere.widget.Toast;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.whm.lib.box_Selection;
import com.example.whm.lib.buyrecord_Selection;
import com.example.whm.model.Address;
import com.example.whm.model.Box;
import com.example.whm.model.Item;
import com.example.whm.model.Order;
import com.example.whm.model.SubscribeItem;
import com.example.whm.model.SubscribeRecord;


public class MySubScribeFragment extends Fragment implements OnItemClickListener,OnItemLongClickListener{

	private AQuery aq; 
	private AQuery aq2;
	
	private String topic;
	Address add;
	Map<String, String> map;
	List<SubscribeRecord> boxs;
	int num=0;
	int price=0;
	int tag;
	Spinner sp;
	ListPopupWindow popup;
	
	RadioGroup radioButtonGroup;
	ProgressDialog dialog;
	adapter adap;
	TextView num_t;
	TextView price_t;
	List<String> longselect=new ArrayList<String>();
	buyrecord_Selection   mCallback;
	boolean isload=false;
	
	
    @Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
    	View view = inflater.inflate(R.layout.myorder_fragment, container, false); 
    	aq=new AQuery(getActivity());
    	aq2=new AQuery(getActivity(), view);
    	
    	return view;
	}






	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		
		init();
		
	}


	ListView list;
public void init(){
	
	  String url="http://"+Whm_app.api_url+":9000/api/user_subscribe";
	  AjaxCallback<String> cb = new AjaxCallback<String>();        
	  cb.url(url).type(String.class).weakHandler(this, "ui");
	  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
  	String cookiename=sp.getString("cookie_name",null);
  	String cookievalue=sp.getString("cookie_value",null);
  	if (cookiename!=null&&cookievalue!=null) {
  		cb.cookie(cookiename,cookievalue);               
	}
	  aq.ajax(cb);
  }

  public void ui(String url, String r, AjaxStatus status){
	
	  System.out.println("ui  s="+r); 
	  if (status.getCode()==200) {
		 
		  
		  final String s=r;
		  new Thread( new Runnable() {
			  @Override
			public void run() {
				  // String s1= JSON.parseObject(s).getString("users");
				  
				  //String mapr= JSON.parseObject(s).getString("mapr");
				  String listj= JSON.parseObject(s).getString("list");
				 // map= JSON.parseObject(mapr, Map.class);
				  
				  boxs= JSON.parseArray(listj, SubscribeRecord.class);
				  System.out.println("boxs.size()========="+boxs.size());
				
				  getActivity().runOnUiThread(new Runnable() {
					  
					  @Override
					  public void run() {
						  Toast.makeText(getActivity(), "boxs.size()="+boxs.size(), 1000).show();
						  if (isload) {
							  show_dialog(false);
							 
							  adap.setList(boxs);
							  adap.notifyDataSetChanged();
						}else{		
							isload=true;
						  aq2.id(R.id.progress).gone();
						//  aq2.id(R.id.four_layout_line).visible();
						  
						//   list=(ListView) aq2.id(R.id.myorder_fragment_listview).getListView();
						/*  View v=getActivity().getLayoutInflater().inflate(R.layout.four_layout_header, null);
						  View v2=getActivity().getLayoutInflater().inflate(R.layout.four_layout_footer, null);
						   AQuery a=new AQuery(v);
						  AQuery a2=new AQuery(v2);
						  a.id(R.id.four_layout_contact_name).text(add.getContact_name());
						  a.id(R.id.four_layout_contact_phone).text(add.getPhone());
						  a.id(R.id.four_layout_contact_addr).text(add.getDetail_address());
						  a2.find(R.id.four_layout_btn_sure).clicked(MySubScribeFragment.this); 
						   radioButtonGroup=(RadioGroup) a.find(R.id.four_layout_pay).getView();
						  list.addHeaderView(v);
						  list.addFooterView(v2);*/
						 
						  adap=new adapter(boxs);
						  aq2.id(R.id.myorder_fragment_listview).adapter(adap);
						  aq2.id(R.id.myorder_fragment_listview).itemClicked(MySubScribeFragment.this);
						  aq2.id(R.id.myorder_fragment_listview).getListView().setOnItemLongClickListener(MySubScribeFragment.this);
						}
						  //Utility.setListViewHeightBasedOnChildren(list);
					  }
				  });
			  }
		  }).start();
			
		  
	}else{
		Toast.makeText(getActivity(), "request error", 1000).show();
		
	}
	  
  }

  
  
  
  
  
  
  
  class adapter extends BaseAdapter{

		
		List<SubscribeRecord> list;
		public adapter() {
			super();
			// TODO Auto-generated constructor stub
		}
	   
		
		
		public List<SubscribeRecord> getList() {
			return list;
		}



		public void setList(List<SubscribeRecord> list) {
			this.list = list;
		}



		public adapter(List<SubscribeRecord> list) {
			super();
			this.list = list;
		}


		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return list.get(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}

		@Override
		public View getView(int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
		
			if(arg1 == null){
				arg1 = aq.inflate(arg1, R.layout.mysubscribe_fragment_item, arg2);
			}
			if (!longselect.contains(boxs.get(arg0).getId())) {
				arg1.setBackgroundResource(0); 
			}else{
				arg1.setBackgroundResource(R.color.list_seletor); 
			}
			
			SubscribeRecord i = (SubscribeRecord) getItem(arg0);
			System.out.println("JSONObject.toJSONString(i)===="+JSONObject.toJSONString(i));
			AQuery aq = aq2.recycle(arg1);
		    
		
			
			aq.id(R.id.mysubscribe_fragment_name).text(i.getName());
			aq.id(R.id.mysubscribe_fragment_price).text(String.valueOf(i.getSub_price()));
			aq.id(R.id.mysubscribe_fragment_priv_days).text(String.valueOf(i.getValid_days()));
			((LinearLayout)aq.id(R.id.mysubscribe_fragment_priv_list).getView()).removeAllViews();
		    if (i.getSub_items()!=null) {			
		    	for(SubscribeItem item:i.getSub_items()){
		    		TextView myText= new TextView(getActivity());		   
		    		myText.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
		    		myText.setText(item.getDetail_date());
		    		((LinearLayout)aq.id(R.id.mysubscribe_fragment_priv_list).getView()).addView(myText);
		    	}
			}
			
			
		
			 
		   // sp=(Spinner) aq.id(R.id.four_layout_list_spinner).getView();				
		//	sp.setSelection(0, true);
			//sp.setOnItemSelectedListener(FourFragmentOrder.this); 
			 /*v=(TextView) aq.id(R.id.four_layout_text_sp).getTextView();
			v.setText("order");
			v.setOnClickListener(FourFragmentOrder.this);*/
			//showListPopup(v);
		
			return arg1;
		}
		
		
	}
  
 
  public void showListPopup(View anchor) {
      popup = new ListPopupWindow(getActivity());
      popup.setAnchorView(anchor);
      ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_2);  
      adapter.add("order");  
      adapter.add("preorder");  
      adapter.add("subscribe");    
      popup.setAdapter(adapter);
      ListView list=popup.getListView();
      
  //    popup.setWidth(300);
   //   popup.setHeight(400);
    // list.setOnItemSelectedListener();
      //list.setOnItemClickListener(FourFragmentOrder.this);
      //.setOnItemClickListener(FourFragmentOrder.this);
      
  }
  


  @Override
  public void onAttach(Activity activity) {
      super.onAttach(activity);

      // This makes sure that the container activity has implemented
      // the callback interface. If not, it throws an exception.
      try {
 	     mCallback = (buyrecord_Selection) activity;
   } catch (ClassCastException e) {
       throw new ClassCastException(activity.toString()
               + " must implement OnHeadlineSelectedListener");
   }
  }




public void set_func(){
	//System.out.println("======order=====set_func===============");
	//Toast.makeText(getActivity(), String.valueOf("sp==null"+sp==null), 1000).show();
	 if (sp!=null) {
		 getActivity().runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					
					sp.setSelection(0,true);
					sp.invalidate();					
					// TODO Auto-generated method stub
			/*		Toast.makeText(getActivity(), "order set_func 1==="+sp.getSelectedItemPosition(), 1000).show();
					
					//sp.performItemClick(null, 0, 0);
					//sp.setAdapter(sp.getAdapter());
					sp.setSelection(2);
					 sp.requestLayout();
					//Toast.makeText(getActivity(), "order set_func 2==="+sp.getSelectedItemPosition(), 1000).show();
				*/
				
					
				}
			});
	}
		
		
	
}


public void show_dialog(boolean b){
	
	if (dialog==null) {
		dialog = new ProgressDialog(getSupportActivity());
	    dialog.setIndeterminate(true);
	    dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	    dialog.setMessage("post");
	}
	if (b) {
		dialog.show();
	}else{
		dialog.dismiss();
	} 
    
}



public void delete(){
	
	Map<String, Object> params = new HashMap<String, Object>();
    params.put("collname", boxs.get(0).getClass().getSimpleName());
    params.put("id", JSONObject.toJSONString(longselect));
    
    
    aq.id(R.id.main_top).id(R.id.buy_re_r_icon).background(R.drawable.abc_ic_menu_moreoverflow_normal_holo_dark);
    longselect.clear();
    mCallback.set_isdelete(false);

    String url="http://"+Whm_app.api_url+":9000/api/delete";
 
    AjaxCallback<String> cb = new AjaxCallback<String>();        
    cb.url(url).type(String.class).weakHandler(MySubScribeFragment.this, "delete_func_result");
    SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
    String cookiename=sp.getString("cookie_name",null);
    String cookievalue=sp.getString("cookie_value",null);
    if (cookiename!=null&&cookievalue!=null) {
    	cb.cookie(cookiename,cookievalue);               
    }else{
	

    }
    show_dialog(true);	
    cb.params(params);
    aq.ajax(cb);
    
}







public void buy_sure(){
 
			// TODO Auto-generated method stub
			 show_dialog(true);
			int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
			View radioButton = radioButtonGroup.findViewById(radioButtonID);
			int idx = radioButtonGroup.indexOfChild(radioButton);
			
			  Map<String, Object> params = new HashMap<String, Object>();
			    params.put("type", idx+1);
			    params.put("tag", 1);
			    params.put("address_id", add.getId());
			  System.out.println("buy_sure===="+JSON.toJSONString(params));
			    
			String url="http://"+Whm_app.api_url+":9000/api/buy_sure_func";
			  AjaxCallback<String> cb = new AjaxCallback<String>();        
			  cb.url(url).type(String.class).weakHandler(this, "sure_func_result");
			  cb.params(params);
			  SharedPreferences sp=((Application)getActivity().getApplication()).getSharedPreferences("whm",Context.MODE_PRIVATE);
			String cookiename=sp.getString("cookie_name",null);
			String cookievalue=sp.getString("cookie_value",null);
			if (cookiename!=null&&cookievalue!=null) {
				cb.cookie(cookiename,cookievalue);               
			}
		    aq.ajax(cb);
		
	
	
}

public void delete_func_result(String url, String r, AjaxStatus status){
	  show_dialog(false);
	  //System.out.println("sure_func_result========="+r);
	//  System.out.println("sure_func_result status.getCode()========="+status.getCode());
	//  System.out.println("sure_func_result url========="+url);
	  if (status.getCode()==200) {
		
		 String re=JSON.parseObject(r).getString("result");
		 if (re.equals("ok")) {
		     init();
		}else if(re.equals("login_error")){
			
			Toast.makeText(getActivity(), String.valueOf("login error,please again"), 1000).show();
		}
		 
	 }else{		 
		 Toast.makeText(getActivity(), String.valueOf("post error,please again"), 1000).show();
	 }
}



public void refresh(){
	show_dialog(true);
	init();
	
}







@Override
public void onItemClick(android.widget.AdapterView<?> arg0, View arg1,
		int arg2, long arg3) {
	// TODO Auto-generated method stub
	if (longselect.isEmpty()) {
		Intent inte=new Intent(getActivity(), MySubscribeDetail.class);
		  if (inte.getExtras()!=null) {
			  inte.getExtras().putString("sub", JSONObject.toJSONString(boxs.get(arg2)));
		}else{
			Bundle b=new Bundle();
			b.putString("sub", JSONObject.toJSONString(boxs.get(arg2)));
			inte.putExtras(b);
		}
		  startActivity(inte);
	}else{
		if (!longselect.contains(boxs.get(arg2).getId())) {
			longselect.add(boxs.get(arg2).getId());
			arg1.setBackgroundResource(R.color.list_seletor); 
		}else{
			longselect.remove(boxs.get(arg2).getId());
			arg1.setBackgroundResource(0); 
		}
		if (!longselect.isEmpty()) {
			mCallback.set_isdelete(true);
		}else{
			aq.id(R.id.main_top).id(R.id.buy_re_r_icon).background(R.drawable.abc_ic_menu_moreoverflow_normal_holo_dark);
			mCallback.set_isdelete(false);
		}
	}
	 
}






@Override
public boolean onItemLongClick(android.widget.AdapterView<?> arg0, View arg1,
		int arg2, long arg3) {
	// TODO Auto-generated method stub
	if (!longselect.contains(boxs.get(arg2).getId())) {
		longselect.add(boxs.get(arg2).getId());
		arg1.setBackgroundResource(R.color.list_seletor); 		
		aq.id(R.id.main_top).id(R.id.buy_re_r_icon).background(R.drawable.abc_ic_menu_delete);
		mCallback.set_isdelete(true);
	}
	
	System.out.println("index========="+arg2);
	Toast.makeText(getActivity(), "longselect.size()==="+longselect.size(), 1000).show();
	return true;
}

    
 
}
